<!--
 * @Date: 2022-03-25 13:32:00
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-03-25 14:46:03
 * @FilePath: \vue3Components\src\components\chooseArea\ChooseArea.vue
 * @Description: 省市区选择器
-->
<template>
  <div>
    <el-select clearable class="m-2" placeholder="请选择省份" size="large" v-model="province">
      <el-option v-for="item in allAreas" :key="item.code" :value="item.code" :label="item.name"></el-option>
    </el-select>
    <el-select
      clearable
      :disabled="!province"
      class="m-2"
      style="margin: 0 20px;"
      placeholder="请选择城市"
      size="large"
      v-model="city"
    >
      <el-option v-for="item in cities" :key="item.code" :value="item.code" :label="item.name" />
    </el-select>
    <el-select
      clearable
      :disabled="!city || !province"
      class="m-2"
      placeholder="请选择区域"
      size="large"
      v-model="area"
    >
      <el-option v-for="item in areas" :key="item.code" :value="item.code" :label="item.name" />
    </el-select>
  </div>
</template>
 <script lang='ts' setup>
import { ref, watch } from 'vue';
import allAreas from './pca-code.json'
export interface AreaData {
  name: string,
  code: string,
  children?: AreaData[]
}
export interface Data {
  name: string,
  code: string
}
let province = ref<string>('')
let city = ref<string>('')
let area = ref<string>('')
let cities = ref<AreaData[]>([])
let areas = ref<AreaData[]>([])
const emits = defineEmits(['changeArea'])
watch(() => province.value, val => {
  if (val) {
    cities.value = allAreas.find((item) => {
      return item.code == province.value
    })!.children!
  }
  city.value = ''
  area.value = ''
})
watch(() => city.value, val => {
  if (val) {
    areas.value = cities.value.find((item) => {
      return item.code == city.value
    })!.children!
  }
  area.value = ''
})
watch(() => area.value, val => {
  if (val) {
    let provinceData: Data = {
      name: allAreas.find(item => item.code == province.value)!.name,
      code: province.value
    }
    let cityData: Data = {
      name: cities.value.find(item => item.code == city.value)!.name,
      code: city.value
    }
    let areaData: Data = {
      name: areas.value.find(item => item.code == val)!.name,
      code: area.value
    }
    const finallData = {
      province: provinceData,
      city: cityData,
      area: areaData
    }
    emits('changeArea', finallData)
  }

})

</script>
<style lang='less' scoped>
</style>
